package com.dhnsoft.education.service.order.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dhnsoft.education.entity.order.Order;
import com.dhnsoft.education.entity.order.PayLog;
import com.dhnsoft.education.handle.EduException;
import com.dhnsoft.education.mapper.order.PayLogMapper;
import com.dhnsoft.education.service.order.OrderService;
import com.dhnsoft.education.service.order.PayLogService;
import com.dhnsoft.education.utils.HttpClient;
import com.dhnsoft.education.utils.order.ConstantWxPayUtils;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author 代浩楠
 * @since 2022-04-14
 */
@Service
public class PayLogServiceImpl extends ServiceImpl<PayLogMapper, PayLog> implements PayLogService {

    @Autowired
    private OrderService orderService;
    //生成微信二维码接口
    @Override
    public Map createNative(String orderNo) {
        try {
            //1.根据订单号查询订单信息
            QueryWrapper<Order> wrapper = new QueryWrapper<>();
            wrapper.eq("order_no",orderNo);
            Order order = orderService.getOne(wrapper);
            //2.使用map设置生成二维码需要的参数
            Map map = new HashMap();
            map.put("appid", ConstantWxPayUtils.WX_PAY_ID);//微信id
            map.put("mch_id",ConstantWxPayUtils.WX_PAY_PARTNER);//商户号
            map.put("nonce_str", WXPayUtil.generateNonceStr());//生成随机字符串
            map.put("body",order.getCourseTitle());//课程标题
            map.put("out_trade_no",orderNo);//二维码唯一标识
            map.put("total_fee",order.getTotalFee().multiply(new BigDecimal("100")).longValue()+"");
            /*
            * TODO 如果上线后要改ip地址
            * */
            map.put("spbill_create_ip","127.0.0.1");//支付ip地址
            map.put("notify_url",ConstantWxPayUtils.WX_PAY_NOTIFY_URL);//回调地址
            map.put("trade_type","NATIVE");//支付类型
            //3.发送httpclient请求，传递参数xml格式,微信支付提供的固定的地址
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //设置xml格式参数
            client.setXmlParam(WXPayUtil.generateSignedXml(map,ConstantWxPayUtils.WX_PAY_PARTNER_KEY));
            client.setHttps(true);
            //执行请求发送
            client.post();
            //4.得到发送请求返回结果
            //返回的内容是用xml格式返回
            String content = client.getContent();
            //把xml格式转换成map集合,把map集合返回,该map只有支付二维码没有别的信息，所以需要封装别的信息
            Map<String,String> resultMap = WXPayUtil.xmlToMap(content);
            //封装别的信息到map集合中，如订单号，课程名称
            Map m = new HashMap();
            m.put("out_trade_no",orderNo);//订单号
            m.put("course_id",order.getCourseId());
            m.put("total_fee",order.getTotalFee());
            m.put("result_code",resultMap.get("result_code"));//二维码状态码
            m.put("code_url",resultMap.get("code_url"));//二维码地址
            return m;

        }catch (Exception e){
            throw new EduException(20001,"生成二维码失败");
        }
    }
    //根据订单号查询订单状态
    @Override
    public Map<String, String> queryPayStatus(String orderNo) {
        try {
            //1.封装参数
            Map m = new HashMap();
            m.put("appid",ConstantWxPayUtils.WX_PAY_ID);
            m.put("mch_id",ConstantWxPayUtils.WX_PAY_PARTNER);
            m.put("out_trade_no",orderNo);//订单号
            m.put("nonce_str",WXPayUtil.generateNonceStr());
            //2.发送httpclient请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(m,ConstantWxPayUtils.WX_PAY_PARTNER_KEY));
            client.setHttps(true);
            client.post();
            //3.返回第三方数据
            //返回的内容是用xml格式返回
            String xml = client.getContent();
            Map<String,String> resultMap = WXPayUtil.xmlToMap(xml);
            return resultMap;
        }catch (Exception e){
            return null;
        }
    }
    //向支付表中添加记录，更新订单状态
    @Override
    public void updateOrderStatus(Map<String, String> map) {
        //从map中获取订单号
        String orderNo = map.get("out_trade_no");
        //根据订单号查询订单信息
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);
        Order order = orderService.getOne(wrapper);

        //更新订单表中订单状态
        if(order.getStatus().intValue()==1){
            return;
        }
        order.setStatus(1);//1.支付 0.未支付
        orderService.updateById(order);
        //向支付表添加支付记录
        PayLog tPayLog = new PayLog();
        tPayLog.setOrderNo(orderNo);//支付订单号
        tPayLog.setPayTime(new Date());//支付时间
        tPayLog.setPayType(1);//支付类型 1.微信 2.支付宝
        tPayLog.setTotalFee(order.getTotalFee());//总金额(分)
        tPayLog.setTradeState(map.get("trade_state"));//支付状态
        tPayLog.setTransactionId(map.get("transaction_id"));//订单流水号
        tPayLog.setAttr(JSONObject.toJSONString(map));//存储其他值,用json字符串存储
        baseMapper.insert(tPayLog);
    }
}
